package com.ybzl.quartz.task;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.QueryApi;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.ybzl.common.utils.spring.ApplicationContextHolder;
import com.ybzl.quartz.config.InfluxConn;
import com.ybzl.quartz.config.InfluxPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 环境指标数据任务
 */
@Slf4j
@Component("envirmtCollectTask")
public class EnvirmtCollectTask {

    public void execute() {
        InfluxPool influxPool = ApplicationContextHolder.getBean(InfluxPool.class);
        InfluxConn conn = null;
        try {
            List<Map<String, Object>> list = new ArrayList<>();

            //从时序库获取数据
            String flux = "from(bucket: \"_tasks\")\n" +
                    "  |> range(start: -10s)\n" +
                    "  |> filter(fn: (r) => r[\"_measurement\"] == \"environment\")";
            conn = influxPool.borrowObject();
            InfluxDBClient influxDBClient = conn.getInfluxDB();
            QueryApi queryApi = influxDBClient.getQueryApi();
            List<FluxTable> tables = queryApi.query(flux);
            if (!ObjectUtils.isEmpty(tables)) {
                tables.forEach(obj -> {
                    List<FluxRecord> record = obj.getRecords();
                    record.forEach(tmp -> {
                        Map<String, Object> ds = tmp.getValues();
                        String aa = String.valueOf(ds.get("eqd")) + "-->" + String.valueOf(ds.get("_time")) + "-->" + String.valueOf(ds.get("_field")) + "-->" + String.valueOf(ds.get("_value"));

                        System.out.println(aa);


                    });
                });
            }
        } catch (Exception e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            if (null != conn) {
                influxPool.returnObject(conn);
            }
        }
    }
}
